package com.lxq.LeetCode.simplifyPath;

public class Solution {
    public static void main(String[] args) {
        System.out.println(simplifyPath("/a//b////c/d//././/.."));
    }

    public static String simplifyPath(String path) {
        StringBuffer sb = new StringBuffer();
        sb.append("/");
        int nextDelimiter, pPath = 0;
        if (path.charAt(path.length() - 1) != '/') {
            path = path + "/";
        }
        while (true) {
            while (pPath < path.length() - 1 && path.charAt(pPath + 1) == '/') {
                pPath++;
            }
            if (pPath == path.length() - 1) {
                break;
            }
            nextDelimiter = path.indexOf('/', pPath + 1);
            if (nextDelimiter == -1) {
                break;
            }
            String tempPath = path.substring(pPath + 1, nextDelimiter);
            if (tempPath.equals("..")) {
                int start = sb.lastIndexOf("/");
                if (start != 0) {
                    sb.delete(start, sb.length());
                } else {
                    sb.delete(start + 1, sb.length());
                }
            } else if (!tempPath.equals(".")) {
                if (sb.length() == 1) {
                    sb.append(tempPath);
                } else {
                    sb.append("/").append(tempPath);
                }

            }
            pPath = nextDelimiter;
        }

        return sb.toString();
    }
}
